import path from 'path';
import got from 'got';
import { fileURLToPath } from 'url';
// import { Worker } from 'worker_threads';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// const playThread = new Worker(path.resolve(__dirname, 'play.js'));

/**
 * @type {Electron.BrowserWindow | null}
 */
let win;

// playThread.stdout.on('data', (data) => {
//     console.log('worker: ', data.toString());
// });

async function tts(text) {
    const buffer = await got.get(`http://localhost:9880?text=${text}`).buffer();
    win.webContents.send('speak', text, buffer);
    // playThread.postMessage(buffer, [buffer.buffer]);
    queue.shift();
    if (queue.length > 0) {
        tts(queue[0]);
    }
}

const queue = [];

export function speak(sentence, mainWin) {
    win = mainWin;
    sentence.split(/[,，.。!！?？：；“‘”’]/).forEach((text) => {
        text = text.replace(/[^\u4e00-\u9fa5]/g, '');
        if (!text) {
            return;
        }
        console.log(`[TTS] ${text}`);
        queue.push(text);
        if (queue.length === 1) {
            tts(text);
        }
    });
}





